import api from '@/utils/api'

// 用于处理研究者信息的辅助函数
function processResearcherInfo(info) {
  if (!info) return null;
  
  // 检查长文本，可能包含不需要的内容
  if (typeof info === 'string' && info.length > 30) {
    // 尝试从文本中提取有意义的研究者信息
    if (info.includes('，')) {
      return info.split('，')[0];
    }
    if (info.includes('今日')) {
      return info.split('今日')[0];
    }
    // 限制长度
    return info.substring(0, 30) + '...';
  }
  
  return info;
}

const state = {
  projects: [],
  currentProject: null,
  loading: false,
  error: null
}

const getters = {
  allProjects: state => state.projects,
  activeProjects: state => state.projects.filter(p => p.status !== 'DELETED' && p.status !== 'COMPLETED'),
  completedProjects: state => state.projects.filter(p => p.status === 'COMPLETED'),
  currentProject: state => state.currentProject,
  projectsLoading: state => state.loading,
  projectsError: state => state.error
}

const mutations = {
  SET_PROJECTS(state, projects) {
    state.projects = projects
  },
  ADD_PROJECT(state, project) {
    state.projects.push(project)
  },
  SET_CURRENT_PROJECT(state, project) {
    state.currentProject = project
  },
  UPDATE_PROJECT(state, updatedProject) {
    const index = state.projects.findIndex(p => p.id === updatedProject.id)
    if (index !== -1) {
      state.projects.splice(index, 1, updatedProject)
    }
    if (state.currentProject && state.currentProject.id === updatedProject.id) {
      state.currentProject = updatedProject
    }
  },
  DELETE_PROJECT(state, projectId) {
    state.projects = state.projects.filter(p => p.id !== projectId)
    if (state.currentProject && state.currentProject.id === projectId) {
      state.currentProject = null
    }
  },
  SET_LOADING(state, loading) {
    state.loading = loading
  },
  SET_ERROR(state, error) {
    state.error = error
  },
  CLEAR_ERROR(state) {
    state.error = null
  }
}

const actions = {
  async fetchProjects({ commit }) {
    commit('SET_LOADING', true)
    commit('CLEAR_ERROR')
    try {
      // 使用正确的API路径，符合API文档
      const response = await api.get('/api/projects')
      
      if (response.status === 200) {
        commit('SET_PROJECTS', response.data)
        return response.data
      } else {
        throw new Error('获取项目列表失败: ' + response.statusText)
      }
    } catch (error) {
      commit('SET_ERROR', error.response?.data?.message || 'Failed to fetch projects')
      throw error
    } finally {
      commit('SET_LOADING', false)
    }
  },
  
  // 获取活跃项目列表（未删除的项目）
  async fetchActiveProjects({ commit }) {
    commit('SET_LOADING', true)
    commit('CLEAR_ERROR')
    try {
      // 使用正确的API路径，符合API文档
      const response = await api.get('/api/projects')
      
      if (response.status === 200) {
        // 过滤活跃项目
        const activeProjects = response.data.filter(p => p.status !== 'DELETED' && p.status !== 'COMPLETED');
        commit('SET_PROJECTS', activeProjects)
        return { success: true, projects: activeProjects }
      } else {
        throw new Error('获取项目列表失败: ' + response.statusText)
      }
    } catch (error) {
      console.error('获取活跃项目列表失败:', error)
      commit('SET_ERROR', error.message || '获取项目列表失败')
      throw error
    } finally {
      commit('SET_LOADING', false)
    }
  },
  
  // 获取所有项目列表（包括已删除的）
  async fetchAllProjects({ commit }) {
    commit('SET_LOADING', true)
    commit('CLEAR_ERROR')
    try {
      // 使用正确的API路径，符合API文档
      const response = await api.get('/api/projects')
      
      if (response.status === 200) {
        return { success: true, projects: response.data }
      } else {
        throw new Error('获取所有项目列表失败: ' + response.statusText)
      }
    } catch (error) {
      console.error('获取所有项目列表失败:', error)
      commit('SET_ERROR', error.message || '获取所有项目列表失败')
      throw error
    } finally {
      commit('SET_LOADING', false)
    }
  },
  
  // 从区块链直接获取项目列表
  async fetchBlockchainProjects({ commit }) {
    try {
      commit('SET_LOADING', true)
      
      // 使用正确的API路径，符合API文档
      const response = await api.get('/api/medical-crowdsourcing/projects/blockchain')
      
      // 数据成功返回
      if (response.status === 200) {
        commit('SET_PROJECTS', response.data)
        return { success: true, projects: response.data }
      } else {
        commit('SET_ERROR', '获取区块链项目失败: ' + response.statusText)
        return { success: false, error: response.statusText }
      }
    } catch (error) {
      console.error('获取区块链项目失败:', error)
      commit('SET_ERROR', error.message || '获取区块链项目失败')
      return { success: false, error: error.message }
    } finally {
      commit('SET_LOADING', false)
    }
  },
  
  async fetchProject({ commit }, projectId) {
    commit('SET_LOADING', true)
    commit('CLEAR_ERROR')
    try {
      // 使用区块链API的正确端点
      const [basic1Response, basic2Response, timesResponse] = await Promise.all([
        api.get(`/api/medical-crowdsourcing/projects/${projectId}/basic1`),
        api.get(`/api/medical-crowdsourcing/projects/${projectId}/basic2`),
        api.get(`/api/medical-crowdsourcing/projects/${projectId}/times`)
      ]);
      
      // 从多个API响应组装完整的项目数据
      const project = {
        id: projectId,
        title: basic1Response.data[0] || '未命名项目',
        description: basic1Response.data[1] || '暂无描述',
        researcherInfo: processResearcherInfo(basic1Response.data[2]) || '暂无研究者信息',
        // 添加研究者ID，默认使用当前登录用户的ID
        researcherId: localStorage.getItem('userId') || null,
        completed: basic2Response.data[0] || false,
        isDeleted: basic2Response.data[1] || false,
        creationTime: timesResponse.data[0] ? parseInt(timesResponse.data[0]) : null,
        lastUpdateTime: timesResponse.data[1] ? parseInt(timesResponse.data[1]) : null,
        deletionTime: timesResponse.data[2] ? parseInt(timesResponse.data[2]) : null,
        deletionReason: basic2Response.data[2] || '',
        dataHash: basic2Response.data[3] || '',
        // 处理日期显示
        createdAt: timesResponse.data[0] ? new Date(parseInt(timesResponse.data[0])) : null,
        lastUpdatedAt: timesResponse.data[1] ? new Date(parseInt(timesResponse.data[1])) : null,
        deletedAt: timesResponse.data[2] ? new Date(parseInt(timesResponse.data[2])) : null
      };
      
      // 从完成状态和删除状态设置显示状态
      if (project.isDeleted) {
        project.status = 'DELETED';
      } else if (project.completed) {
        project.status = 'COMPLETED';
      } else {
        project.status = 'ACTIVE';
      }
      
      commit('SET_CURRENT_PROJECT', project)
      return project
    } catch (error) {
      commit('SET_ERROR', error.response?.data?.message || 'Failed to fetch project details')
      throw error
    } finally {
      commit('SET_LOADING', false)
    }
  },
  
  async createProject({ commit, dispatch }, projectData) {
    commit('SET_LOADING', true)
    commit('CLEAR_ERROR')
    try {
      // 预处理研究者信息
      const researcherInfo = processResearcherInfo(projectData.researcherInfo || projectData.researcherName);
      
      // 使用正确的API路径和字段名称，符合区块链API格式
      const projectResponse = await api.post('/api/medical-crowdsourcing/projects', {
        _title: projectData.title,
        _description: projectData.description,
        _researcherInfo: researcherInfo
      })
      
      // 刷新项目列表
      await dispatch('fetchProjects')
      
      return projectResponse.data
    } catch (error) {
      commit('SET_ERROR', error.response?.data?.message || 'Failed to create project')
      throw error
    } finally {
      commit('SET_LOADING', false)
    }
  },
  
  async completeProject({ commit, dispatch }, projectId) {
    commit('SET_LOADING', true)
    commit('CLEAR_ERROR')
    try {
      // 使用正确的API路径，符合API文档
      await api.post(`/api/projects/${projectId}/close`, {});
      
      // 重新获取项目信息
      await dispatch('fetchProject', projectId);
      
      return { success: true }
    } catch (error) {
      commit('SET_ERROR', error.response?.data?.message || 'Failed to complete project')
      throw error
    } finally {
      commit('SET_LOADING', false)
    }
  },
  
  async deleteProject({ commit }, projectId) {
    commit('SET_LOADING', true)
    commit('CLEAR_ERROR')
    try {
      // 使用正确的API路径，符合API文档
      await api.delete(`/api/projects/${projectId}`);
      
      // 从状态中移除项目
      commit('DELETE_PROJECT', projectId);
      
      return { success: true }
    } catch (error) {
      commit('SET_ERROR', error.response?.data?.message || 'Failed to delete project')
      throw error
    } finally {
      commit('SET_LOADING', false)
    }
  },
  
  async updateProject({ commit, dispatch }, { projectId, data }) {
    commit('SET_LOADING', true)
    commit('CLEAR_ERROR')
    try {
      // 确保存在研究者信息字段并预处理
      if (data.researcherInfo) {
        data.researcherInfo = processResearcherInfo(data.researcherInfo);
      }
      
      console.log('尝试更新项目，ID:', projectId, '数据:', data);
      
      // 使用用户指定的API端点
      const API_ENDPOINT = `/api/medical-crowdsourcing/projects/${projectId}/update`;
      console.log('使用API端点:', API_ENDPOINT);
      
      // 使用POST方法
      const response = await api.post(API_ENDPOINT, {
        _title: data.title,
        _description: data.description,
        _researcherInfo: data.researcherInfo,
        _updateReason: data.updateReason || "更新项目信息"
      });
      
      console.log('项目更新成功:', response.data);
      
      // 重新获取项目信息
      await dispatch('fetchProject', projectId);
      
      return { success: true, project: response.data }
    } catch (error) {
      console.error('更新项目失败:', error);
      console.error('错误详情:', error.response?.data || '无详细错误信息');
      console.error('请求配置:', error.config || '无请求配置信息');
      commit('SET_ERROR', error.response?.data?.message || 'Failed to update project')
      throw error
    } finally {
      commit('SET_LOADING', false)
    }
  }
}

export default {
  namespaced: true,
  state,
  getters,
  actions,
  mutations
} 